package com.zhentao.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.loginUser.pojo.TMenu;
import com.zhentao.service.TMenuService;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.function.Supplier;
@Component
public class DyConfig implements AuthorizationManager<RequestAuthorizationContext> {
    @Resource
    private TMenuService tMenuService;

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        String uri = context.getRequest().getRequestURI();
        TMenu menu = tMenuService.getOne(Wrappers.<TMenu>lambdaQuery().eq(TMenu::getUrl, uri));
        if(menu==null){
            return new AuthorizationDecision(true);
        }
        String perms = menu.getPerms();
        //获取当前用户的权限集合
        Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();
        //请求路径权限和用户权限对比 如果相等 证明有权限  可以访问
        for(GrantedAuthority authoritie:authorities){
            String authority = authoritie.getAuthority();
            if(authority.equals(perms)){
                return new AuthorizationDecision(true);
            }
        }
        return new AuthorizationDecision(false);
    }
}
